package com.qfedu.java1234.common.security;

import com.qfedu.java1234.common.exception.UserCountLockException;
import com.qfedu.java1234.entity.bo.SysUser;
import com.qfedu.java1234.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName MyUserDetailServiceImpl
 * @Author ykx
 * @Date 2024/4/21 21:20
 * @Version 1.0
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或者密码错误！");
        } else if ("1".equals(sysUser.getStatus())) {
            throw new UserCountLockException("该用户账号已被封禁，具体联系管理员！");
        }
        return new User(sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(Long id) {
        String authority = userService.getUserAuthorityInfo(id);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
